import { createRouter, createWebHashHistory } from "vue-router";
const user = JSON.parse(sessionStorage.getItem("user"));
console.log(user);

const routes = [
  {
    path: "/",
    name: "home",
    component: () => import("../pages/home.vue"),
  },
  {
    path: "/about",
    name: "about",
    component: () => import("../pages/about.vue"),
  },
  {
    path: "/map",
    name: "map",
    component: () => import("../pages/map.vue"),
  },
  {
    path: "/herald",
    name: "herald",
    component: () => import("../pages/herald.vue"),
  },
  {
    path: "/strategy",
    name: "strategy",
    component: () => import("../pages/strategy.vue"),
  },
  {
    path: "/Introcom",
    name: "Introcom",
    component: () => import("../pages/Introcom.vue"),
  },
  {
    path: "/issuance",
    name: "issuance",
    component: () => import("../pages/issuance.vue"),
  },
  {
    path: "/mine",
    name: "mine",
    component: () => import("../pages/mine.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../pages/login.vue"),
  },
  {
    path: "/PromoCode",
    name: "PromoCode",
    component: () => import("../pages/PromoCode.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 添加路由守卫
router.beforeEach((to, from) => {
  // 如果用户未登录且试图访问非登录页面，重定向到登录页面
  if (!user && to.path !== "/login") {
    return { name: "login" }; // 使用命名路由更加可靠
  }

  // 如果用户已登录且访问登录页面，重定向到首页
  if (user && to.path === "/login") {
    return { name: "home" }; // 使用命名路由更加可靠
  }
});

export default router;
